package com.zhxh.nzpos.query;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.zhxh.nzpos.BaseActivity;
import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.barcode.CaptureActivity;
import com.zhxh.nzpos.dao.CategoryDao;
import com.zhxh.nzpos.dao.GoodsDao;
import com.zhxh.nzpos.goods.GoodsItem;
import com.zhxh.nzpos.model.Category;
import com.zhxh.nzpos.model.Goods;
import com.zhxh.nzpos.view.CustomDatePicker;

/**
 * 统计查询--订购查询
 * 
 * @author wangzt
 * 
 */
public class GoodsQueryActivity extends BaseActivity {

	private ArrayList<GoodsItem> items;

	private ArrayList<Goods> goodsItems;
	private GoodsQueryAdapter listAdapter;
	private String[] category_items;
	List<Category> list;
	CategoryDao categoryDao;
	GoodsDao goodsDao;
	EditText fromDate;
	EditText toDate;
	EditText goodsCode;
	Spinner typeSpinner;
	SimpleDateFormat simpleDateFormat;
	SimpleDateFormat simpleDateFormat2;
	private long total;
	private int pageSize = 5;
	private int currentPage = 1;

	private Calendar fromCal = Calendar.getInstance();
	private Calendar toCal = Calendar.getInstance();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_query_goods);
		categoryDao = new CategoryDao(this);
		goodsDao = new GoodsDao(this);
		initViews();
	}

	private void initViews() {

		ListView listView = (ListView) findViewById(R.id.buyin_query_listview);
		items = new ArrayList<GoodsItem>();

		goodsCode = (EditText) findViewById(R.id.buyin_goods_code_et);

		typeSpinner = (Spinner) findViewById(R.id.query_goods_type_spinner);
		/*
		 * ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
		 * getApplicationContext(), R.array.stock_type,
		 * R.layout.custom_spinner_text);
		 * adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown);
		 */

		// List<Category> list = categoryDao.getAll();
		list = categoryDao.getAll();
		category_items = new String[list.size() + 1];
		category_items[0] = "请选择分类";
		for (int i = 0; i < list.size(); i++) {
			Category cate = list.get(i);
			category_items[i + 1] = cate.getCategory();
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, category_items);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpinner.setAdapter(adapter);

		fromDate = (EditText) findViewById(R.id.buyin_from_date);
		toDate = (EditText) findViewById(R.id.buyin_to_date);
		simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		fromDate.setText(simpleDateFormat.format(fromCal.getTime()));
		toDate.setText(simpleDateFormat.format(toCal.getTime()));

		final CustomDatePicker fromPicker = new CustomDatePicker(this,
				fromDate, fromCal);
		fromDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				fromPicker.updateDate();
				fromPicker.show();
			}
		});

		final CustomDatePicker toPicker = new CustomDatePicker(this, toDate,
				toCal);
		toDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				toPicker.updateDate();
				toPicker.show();
			}
		});

		/*
		 * ImageView searchBtn = (ImageView)
		 * findViewById(R.id.buyin_search_btn); searchBtn.setOnClickListener(new
		 * OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { //TODO 搜索
		 * ViewUtil.makeToast(getApplicationContext(), "没有相关信息！"); } });
		 */

		Button scanBtn = (Button) findViewById(R.id.buyin_scan_btn);
		scanBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), CaptureActivity.class);
				startActivityForResult(intent, Constants.SCAN_REQUEST_CODE);
			}
		});
		
		listAdapter = new GoodsQueryAdapter(getLayoutInflater(), items);
		listView.setAdapter(listAdapter);

/*		ImageView cancelBtn = (ImageView) findViewById(R.id.buyin_query_close_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});*/
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == Constants.SCAN_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String ocrStr = intent.getStringExtra(Constants.SCAN_RESULT_EXTRA);
				if (!TextUtils.isEmpty(ocrStr)) {
					goodsCode.setText(ocrStr);
				} else {
					Toast.makeText(getApplicationContext(), "请重新扫描！",
							Toast.LENGTH_LONG).show();
				}

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(), "请重新扫描！",
						Toast.LENGTH_LONG).show();
			}
		}
	}
	
	public void search(View view) {
		// finish();
		currentPage = 1;
		doSearch(view);
		doGetCount(view);

	}

	public void page_next(View view) {
		
		if (currentPage * pageSize <= total)
		{
			currentPage++;
			doSearch(view);
		}
			
		
	}

	public void page_previous(View view) {

		currentPage--;

		if (currentPage < 1) {
			currentPage = 1;
		}

		doSearch(view);

	}

	public void doSearch(View view) {

		String cateId = null;
		int position = typeSpinner.getSelectedItemPosition();
		if (position != 0) {
			Category cate = list.get(position - 1);
			cateId = cate.getId();
		}
		String identifier = goodsCode.getText().toString();
		Date btime;
		Date etime;
		try {
			btime = simpleDateFormat.parse(fromDate.getText().toString());
			etime = simpleDateFormat2.parse(toDate.getText().toString()+" 23:59:59");

			goodsItems = goodsDao.getScrollData(cateId, identifier,
					btime.getTime(), etime.getTime(), currentPage, pageSize);
			items.clear();
			if (goodsItems.size() > 0) {
				for (Goods goods : goodsItems) {
					GoodsItem item = copyProperties(goods);
					items.add(item);
				}
			}
			if (listAdapter != null) {
				listAdapter.notifyDataSetChanged();
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doGetCount(View view) {
        
		String cateId = null;
		int position = typeSpinner.getSelectedItemPosition();
		if (position != 0) {
			Category cate = list.get(position - 1);
			cateId = cate.getId();
		}
		String identifier = goodsCode.getText().toString();
		Date btime;
		Date etime;
		try {
			btime = simpleDateFormat.parse(fromDate.getText().toString());
			etime = simpleDateFormat2.parse(toDate.getText().toString()+" 23:59:59");

			total = goodsDao.getCount(cateId, identifier, btime.getTime(),
					etime.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.i("count============", total+"");
	}

	private GoodsItem copyProperties(Goods goods) {
		GoodsItem item = new GoodsItem();
		item.setId(goods.getId());
		item.setCategoryId(goods.getCategoryId());
		item.setCategoryName(goods.getCategoryName());
		item.setName(goods.getName());
		item.setNote(goods.getNote());
		item.setPrice1(goods.getPrice1());
		item.setPrice2(goods.getPrice2());
		item.setSpecification(goods.getSpecification());
		item.setUnits1(goods.getUnits1());
		item.setUnits2(goods.getUnits2());
		item.setCode(goods.getCode());
		return item;
	}

}
